package com.me.db;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.me.blood.App;

import java.util.concurrent.atomic.AtomicInteger;

public class DatabaseManager {

    private static DatabaseManager instance;

    private static SQLiteOpenHelper mDatabaseHelper;

    private SQLiteDatabase mDatabase;

    private final AtomicInteger counter = new AtomicInteger(0);

    public static synchronized DatabaseManager getInstance() {
        if (instance == null) {
            instance = new DatabaseManager();
            mDatabaseHelper = new DatabaseHelper(App.getApp());
        }
        return instance;
    }

    public synchronized SQLiteDatabase openDatabase() {
        try {
            if (mDatabase == null) {
                mDatabase = mDatabaseHelper.getWritableDatabase();
                counter.set(0);
            } else if (counter.get() == 0) {
                mDatabase = mDatabaseHelper.getWritableDatabase();
            }
            counter.incrementAndGet();
            return mDatabase;
        } catch (Throwable e) {
            return null;
        }
    }

    public synchronized void closeDatabase() {
        if (counter.decrementAndGet() == 0) {
            if (mDatabase != null) {
                mDatabase.close();
                mDatabase = null;
            }
        }
    }
}